<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择账号类型" clearable>
          <el-option
              v-for="dict in t_mer_user_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              v-show="dict.value !== '20'"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tmeruser:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDelete"
            v-hasPermi="['system:tmeruser:remove']"
            :disabled="multiple"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tmeruserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="账号类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="t_mer_user_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName"/>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="允许核销" align="center" prop="isVerify">
        <template #default="scope">
          <div class="padRight" v-if="scope.row.type == 20 || scope.row.type == 2">
            <el-switch
                v-model="scope.row.isVerify"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
            ></el-switch>
          </div>
          <span v-else>--</span>
        </template>
        <!-- :disabled="userStore.userType == 0 ? false: true"  -->
        <!-- <template #default="scope">
          <span v-if="scope.row.isVerify == 1">是</span>
          <span v-else>否</span>
          <dict-tag :options="t_mer_user_type" :value="scope.row.type"/>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:tmeruser:edit']">修改
          </el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:tmeruser:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商家账号对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tmeruserRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-tooltip placement="top-start">
                <template #content>
                  小程序账号：即授权小程序用户核销此商家订单的权限；<br />商家账号：即绑定此商家后台账号；<br />业务员：即绑商家关联的业务员<br />
                </template>
              <el-form-item label="账号类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择账号类型" @change="chooseType" :disabled="disableNum">
                  <el-option
                      v-for="dict in t_mer_user_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                      v-show="dict.value !== '20'"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联账号" prop="userId">
              <user-select :disabledValue="disableNum" :key="typeNum" v-model="form.userId" :userType="userType" :modelValue="form.userId" :nameValue="form.userName"></user-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="form.type == 20 || form.type == 2">
          <el-col :span="12">
            <el-form-item label="允许核销" prop="isVerify">
              <el-switch
                  v-model="form.isVerify"
                  active-value="1"
                  inactive-value="0"
                  class="drawer-switch"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tmeruser">
import {listTmeruser, getTmeruser, delTmeruser, addTmeruser, updateTmeruser} from "@/api/system/tmeruser";
import UserSelect from "@/components/UserSelect/index"
import {nextTick} from "vue";

const route = useRoute();


const {proxy} = getCurrentInstance();
const {t_mer_user_type} = proxy.useDict('t_mer_user_type');

const tmeruserList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userType = ref("100");
const typeNum = ref(0);
const disableNum = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merId: undefined,
    type: undefined,
    userId: undefined,
    isVerify: undefined,
  },
  rules: {
    // merId: [
    //   { required: true, message: "商家ID不能为空", trigger: "blur" }
    // ],
    type: [
      {required: true, message: "账号类型不能为空", trigger: "change"}
    ],
    userId: [
      {required: true, message: "用户ID不能为空", trigger: "blur"}
    ],
    // isVerify: [
    //   {required: true, message: "允许核销不能为空", trigger: "blur"}
    // ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询商家账号列表 */
function getList() {
  queryParams.value.merId = route.params.id

  loading.value = true;
  listTmeruser(queryParams.value).then(response => {
    tmeruserList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function chooseType() {
  typeNum.value += 1
  userType.value = form._object.form.type
  form.value.userId = ""

}

// 表单重置
function reset() {
  // typeNum.value += 1
  form.value = {
    id: undefined,
    merId: undefined,
    type: undefined,
    userId: undefined,
    isVerify: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined,
    userName: undefined
  };
  proxy.resetForm("tmeruserRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  disableNum.value = 0
  
  reset();
  typeNum.value += 1
  userType.value = 100
  rules._object.rules.userId[0].required = true
  open.value = true;
  title.value = "添加商家账号";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  disableNum.value = 1
  reset();
  const _id = row.id || ids.value
  rules._object.rules.userId[0].required = false
  getTmeruser(_id).then(response => {
    response.data.isVerify = response.data.isVerify.toString()
    form.value = response.data;
    form.value.userName = row.userName
   
    userType.value = response.data.type
    typeNum.value += 1
    open.value = true;
    title.value = "修改商家账号";
  });
}

/** 提交按钮 */
function submitForm() {
  form.value.merId = route.params.id;
  proxy.$refs["tmeruserRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTmeruser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTmeruser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商家账号编号为"' + _ids + '"的数据项？').then(function () {
    return delTmeruser(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tmeruser/export', {
    ...queryParams.value
  }, `tmeruser_${new Date().getTime()}.xlsx`)
}

/** 用户状态修改  */
function handleStatusChange(row) {
  proxy.$modal.confirm('确定要更改核销状态吗').then(function () {
    return updateTmeruser(row)
  }).then(() => {
    proxy.$modal.msgSuccess("修改成功");
    open.value = false;
  //   getList();
    getList();
  }).catch(function () {
    getList();
  });
};

getList();
</script>
